import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import Users from '../components/Users.vue'
import Welcome from '../components/Welcome.vue'
import Roles from '../components/Roles.vue'
import Rights from '../components/Rights.vue'
import Params from '../components/Params.vue'
import Goods from '../components/Goods.vue'
import Categories from '../components/Categories.vue'
import Orders from '../components/Orders.vue'
import Reports from '../components/Reports.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path:'/login',
    component:Login
  },
  {
    path:'/home',
    component: Home,
    redirect:'/welcome',
    children:[
      {
        path:'/welcome',
        component:Welcome
      },
      {
        path:'/users',
        component:Users
      },
      {
        path:'/roles',
        component:Roles
      },
      {
        path:'/rights',
        component:Rights
      },
      {
        path:'/params',
        component:Params
      },
      {
        path:'/goods',
        component:Goods
      },
      {
        path:'/categories',
        component:Categories
      },
      {
        path:'/orders',
        component:Orders
      },
      {
        path:'/reports',
        component:Reports
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to,from,next) => {
  //登录页面直接放行
  if(to.path === '/login') return next()
  //其余路由需要登录才能放行
  const tokenStr = window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login')
  next()
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
